package com.slaoren.mvvmexamp.ui

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.Exception
import java.lang.reflect.ParameterizedType

abstract class BaseActivity<T : ViewDataBinding, M: ViewModel>:AppCompatActivity() {
    lateinit var mBinding:T
    var mViewModel:M ?=null

    abstract fun getLayoutId():Int

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mBinding = DataBindingUtil.setContentView(
            this,
            getLayoutId()
        )
        mBinding.lifecycleOwner = this

        setVM()
        initView()
        setObserve()
        loadData()
    }

    abstract fun initView()

    open fun setObserve(){

    }
    open fun loadData(){

    }

    private fun setVM(){
        val type = this.javaClass.genericSuperclass //获取泛型
        if (type is ParameterizedType) {
            Log.d("test", "type:"+type.actualTypeArguments.size)
            val targetType = type.actualTypeArguments[1]//获取第二个参数
            Log.d("test", "targetType:"+targetType)
//            mViewModel = ViewModelProvider.AndroidViewModelFactory(application).create(targetType as Class<M>)
            mViewModel = ViewModelProvider(viewModelStore, defaultViewModelProviderFactory)[targetType as Class<M>]

            Log.d("test", "mViewModel BaseActivity:"+mViewModel?.javaClass)
        }
    }
}